import java.util.Arrays;

    public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap(){

        this.elem = new int[10];
    }

//大跟堆
    public void  initElem(int[] array){
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }


    public void createHeap(){
        for (int parent = (usedSize-1-1)/2; parent >= 0 ; parent--) {
            shiftDown(parent,usedSize);
        }

    }

    private void shiftDown( int parent  ,int  len){
        int childe = 2 * parent + 1;
        //最起码 有左孩子
        while ( childe < len){
            if (childe+1 <len &&elem[childe]<elem[childe+1]){
                childe++;
            }
            if (elem[childe] > elem[parent]){
                int tmp = elem[childe];
                elem[childe] = elem[parent];
                elem[parent] = tmp;
                parent = childe;
                childe = 2 * parent + 1;
            }else {
                break;
            }
        }
    }
//小根堆

    public void createHeap2(){
     for (int parent = (usedSize-1-1)/2; parent >= 0 ; parent--) {
            shiftDown2(parent,usedSize);
        }

    }
    private void shiftDown2( int parent  ,int  len){
    int childe = 2 * parent + 1;
    //最起码 有左孩子
    while ( childe < len){
        if (childe+1 <len &&elem[childe]>elem[childe+1]){
            childe++;
        }
        if (elem[childe] < elem[parent]){
            int tmp = elem[childe];
            elem[childe] = elem[parent];
            elem[parent] = tmp;
            parent = childe;
            childe = 2 * parent + 1;
        }else {
            break;
        }
    }
}

//插入
    private void shiftUp(int child){
        int parent = (child - 1)/2;
        while (child > 0){
            if (elem[child] >elem[parent]){
                int tmp = elem[child];
                elem[child] = elem [parent];
                elem[parent] = tmp;
                child = parent;
                parent = (child - 1)/2;
            }else {
                break;
            }

        }
    }

    public void  offer(int val){
        if (isFull()){
            //如果满了进行扩容
            elem = Arrays.copyOf(elem,2*elem.length);

        }
        elem[usedSize++] = val;
        //向上调整

        shiftUp(usedSize-1);
    }
    private boolean isFull(){
        return usedSize == elem.length;
    }


//删除
    public void pop(){
        if (isEmpty()){
            return;
        }
        swap(elem,0,usedSize-1);
        usedSize--;
        shiftDown(0,usedSize);
    }

    private boolean isEmpty(){
        return usedSize == 0;
    }
    private void swap(int[] array,int i, int j ){
        int tmp = array[i];
        array[i] = array [j];
        array[j] = tmp;
    }
}
